const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const config = require('../config')

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.put('/', async function(ctx, next) {
  var user = ctx.request.body
  console.log(user)
  await ctx.connection.query({
    sql: 'insert into user(username,password,email,address) values(?,?,?,?)',
    values: [user.username, user.password, user.email, user.address]
  })
    .then((resp) => ctx.body = resp)
})

router.post('/exits', async function(ctx , next){
   var user = ctx.request.body
   await ctx.connection.query({
     sql: 'select count(*) as isExits from user where username = ?',
     values:[user.username]
   })
   .then((resp) => {
     console.log(resp);
     ctx.body = {'isExits': resp[0].isExits>0 ? true : false}
     return;
   })
})

router.post('/login',async function (ctx , next){
  var user = ctx.request.body
  var result = await ctx.connection.query({
    sql: 'select id,username,email,address from user where username = ? and password = ?',
    values:[user.username,user.password]
  }).then(resp => {
    if(resp.length !== 1){
      ctx.body = {message:'Login failed.'}
    }else{
      var token = jwt.sign(resp[0], config.secretKey)
      ctx.body = Object.assign(resp[0],{token})
    }
  })
})

router.get('/login',async function (ctx , next){
  var user = ctx.currentUser
  ctx.body = user
})

module.exports = router
//create table if not exists user(id int primary key auto_increment,username varchar(255) not null unique,password varchar(255) not null,email varchar(255),address varchar(255));
